<template>
  <a-card :bordered="false">
    <!-- 查询区域 -->
    <div class="table-page-search-wrapper">
      <a-form layout="inline" @keyup.enter.native="searchQuery1">
        <a-row :gutter="24">
          <a-col :xl="4" :lg="7" :md="8" :sm="24">
            <a-form-item label="下单门店">
              <a-cascader
                :options="departModel.departTreeOptions"
                :showSearch="true"
                expand-trigger="hover"
                placeholder=""
                :fieldNames="departModel.fieldNames"
                style="width: 210px"
                v-model="queryParam.selecteddeparts"
              />
            </a-form-item>
          </a-col>
          <a-col :xl="5" :lg="7" :md="8" :sm="24">
            <a-form-item label="下单时间" :required="true">
              <a-range-picker
                :ranges="{ 今天: [moment(), moment()], 近7天:[moment().subtract(7, 'days'),moment()],本月: [moment().startOf('month'), moment().endOf('month')] }"
                v-model="orderDateRange"
                @change="handleChange"
              />
            </a-form-item>
          </a-col>
          <a-col :xl="4" :lg="7" :md="8" :sm="24">
            <!--收银状态（0待支付 1支付成功 2支付失败 3支付撤销  ）-->
            <a-form-item label="支付状态">
              <a-select allowClear defaultValue="1" v-model="queryParam.payStatus">
                <a-select-option v-for="item in payStatus" :key="item.key" :value="item.key">
                  {{ item.val }}
                </a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :xl="4" :lg="7" :md="8" :sm="24">
            <a-form-item label="单据号">
              <a-input v-model="queryParam.orderNo" allowClear></a-input>
            </a-form-item>
          </a-col>
          <a-col :xl="4" :lg="7" :md="8" :sm="24">
            <a-form-item label="商品编码">
              <a-input v-model="queryParam.itemCode" allowClear></a-input>
            </a-form-item>
          </a-col>
          <a-col :xl="4" :lg="7" :md="8" :sm="24">
            <a-form-item label="SKU编码">
              <a-input v-model="queryParam.itemSku" allowClear></a-input>
            </a-form-item>
          </a-col>
          <a-col :xl="4" :lg="7" :md="8" :sm="24">
            <a-form-item label="会员订单">
              <a-select v-model="queryParam.memberFlag" allowClear>
                <a-select-option value="1"> 会员 </a-select-option>
                <a-select-option value="0"> 散客 </a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :xl="4" :lg="7" :md="8" :sm="24">
            <a-form-item label="会员手机号">
              <a-input v-model="queryParam.mobile" allowClear></a-input>
            </a-form-item>
          </a-col>

          <a-col :xl="4" :lg="7" :md="8" :sm="24">
            <span style="float: left; overflow: hidden" class="table-page-search-submitButtons">
              <a-button type="primary" @click="searchQuery1" icon="search">查询</a-button>
              <a-button type="default" @click="searchReset1" icon="reload" style="margin-left: 8px">重置</a-button>
            </span>
          </a-col>
        </a-row>
      </a-form>
    </div>

    <!-- 操作按钮区域 -->
    <div class="table-operator">
      <a-button type="primary" icon="download" @click="handleExportXls1('收银单')">导出订单</a-button>
      <a-button type="primary" icon="download" @click="handleExportDetailXls('收银单商品明细')"
        >导出订单商品明细</a-button
      >
    </div>

    <!-- table区域-begin -->
    <div>
      <div class="ant-alert ant-alert-info" style="margin-bottom: 16px">
        <span class="sum"
          >总交易额(元) <span class="b">{{ orderSum.totalAmount }}</span>
        </span>
        <span class="sum"
          >订单总笔数 <span class="b">{{ orderSum.orderCnt }}</span>
        </span>
        <span class="sum"
          >商品销售总件数 <span class="b">{{ orderSum.prodCnt }}</span>
        </span>
      </div>
      <a-table
        ref="table"
        size="middle"
        bordered
        rowKey="id"
        :columns="columns"
        :dataSource="dataSource"
        :pagination="ipagination"
        :loading="loading"
        class="j-table-force-nowrap"
        @change="handleTableChange"
      >
        <span slot="action" slot-scope="text, record">
          <a @click="handleDetail(record)">详情</a>
        </span>
        <span slot="mobile" slot-scope="text">
          <span v-if="text !== ''">{{ text }}</span>
          <span v-else>散客</span>
        </span>
        <span slot="orderStatus" slot-scope="text">
          <!-- 0新建 1支付成功 2作废 3超时未支付 4已完成  -->
          <a-tag color="orange" v-if="text === 0">新建</a-tag>
          <a-tag color="blue" v-if="text === 1">下单成功</a-tag>
          <a-tag color="orange" v-if="text === 2">作废</a-tag>
          <a-tag color="orange" v-if="text === 3">超时未付</a-tag>
          <a-tag v-if="text === 4">已完成</a-tag>
        </span>
        <span slot="payStatus" slot-scope="text">
          <!-- （0待支付 1支付成功 2支付失败 3支付撤销  ） -->
          <a-tag color="orange" v-if="text === 0">待支付</a-tag>
          <a-tag color="blue" v-if="text === 1">支付成功</a-tag>
          <a-tag color="orange" v-if="text === 2">支付失败</a-tag>
          <a-tag color="orange" v-if="text === 3">支付撤销</a-tag>
        </span>
      </a-table>
    </div>
    <!-- table区域-end -->

    <!-- 表单区域 -->
    <posCashierOrder-modal ref="modalForm" @ok="modalFormOk"></posCashierOrder-modal>
  </a-card>
</template>

<script>
import '@/assets/less/TableExpand.less'
import PosCashierOrderModal from './modules/PosCashierOrderModal'
import { JeecgListMixin } from '@/mixins/JeecgListMixin'
import moment from 'moment'
import { getAction, downFile } from '@/api/manage'
import { queryDepartTreeList1 } from '@/api/api'

export default {
  name: 'PosCashierOrderList',
  mixins: [JeecgListMixin],
  components: {
    PosCashierOrderModal,
  },
  data() {
    return {
      description: '收银单管理页面',
      disableMixinCreated: true,
      departModel: {
        departTreeOptions: [],
        fieldNames: { label: 'title', value: 'value', children: 'children' },
      },
      orderDateRange: [],
      orderSum: {
        orderCnt: 0,
        prodCnt: 0,
        totalAmount: 0,
      },
      shopList: [],
      payStatus: [
        // { key: '0', val: '待支付' },
        { key: '1', val: '支付成功' },
        { key: '2', val: '支付失败' },
        { key: '3', val: '支付撤销' },
      ],
      // 表头
      columns: [
        {
          title: '所属机构',
          align: 'center',
          dataIndex: 'orgName',
        },
        {
          title: '下单门店',
          align: 'center',
          dataIndex: 'shopName',
        },
        {
          title: '单据号',
          align: 'center',
          dataIndex: 'orderNo',
        },
        {
          title: '收银员姓名',
          align: 'center',
          dataIndex: 'operUserName',
        },

        {
          title: '订单状态',
          align: 'center',
          dataIndex: 'orderStatus',
          scopedSlots: { customRender: 'orderStatus' },
        },
        {
          title: '收银时间',
          align: 'center',
          dataIndex: 'operTime',
        },
        {
          title: '付款状态',
          align: 'center',
          dataIndex: 'payStatus',
          scopedSlots: { customRender: 'payStatus' },
        },
        {
          title: '付款时间',
          align: 'center',
          dataIndex: 'payTime',
        },
        {
          title: '会员手机号',
          align: 'center',
          dataIndex: 'mobile',
          scopedSlots: { customRender: 'mobile' },
        },
        {
          title: '商品总件数',
          align: 'center',
          dataIndex: 'prodsNum',
        },
        {
          title: '订单总金额(元)',
          align: 'center',
          dataIndex: 'orderAmount',
        },
        {
          title: '优惠总金额(元)',
          align: 'center',
          dataIndex: 'totalDisAmount',
          customRender: (text) => 0 - text,
        },
        {
          title: '实付总金额(元)',
          align: 'center',
          dataIndex: 'payAmount',
        },
        {
          title: '销售终端',
          align: 'center',
          dataIndex: 'termType',
        },
        {
          title: '操作',
          dataIndex: 'action',
          align: 'center',
          scopedSlots: { customRender: 'action' },
        },
      ],
      url: {
        list: '/cashier/posCashierOrder/list',
        shopListUrl: '/stock/posShop/shopList',
        sumUrl: '/cashier/report/sum',
        exportXlsUrl: 'cashier/posCashierOrder/exportXls',
        exportDetailXlsUrl: 'cashier/posCashierOrder/exportDetailXls',
      },
    }
  },
  computed: {},
  created() {
    this.init()
  },
  methods: {
    moment,
    init(reset) {
      this.queryParam = {}
      this.queryParam.ifHang = 0
      this.orderDateRange = []
      if (!reset) {
        this.$set(this.queryParam, 'payStatus', '1')
      }
      this.loadDepartTree()
      if(!reset){
        this.orderDateRange = [moment().subtract(7, 'days'),moment()]
        this.queryParam.beginTime = moment().subtract(7, 'days').format('YYYY-MM-DD')
        this.queryParam.endTime = moment().format('YYYY-MM-DD')
      }
      this.searchQuery1()
    },
    loadDepartTree() {
      queryDepartTreeList1().then((res) => {
        if (res.success) {
          let departList = res.result
          if (departList.length == 1 && departList[0].orgType == 1) {
            departList = departList[0].children
          }
          this.departModel.departTreeOptions = departList

          this.departModel.departTreeOptions.forEach((x) => {
            if (!x['children']) {
              x['children'] = []
            }
            let allShop = { title: '全部门店', value: '0' }
            x['children'].unshift(allShop)
          })
        }
      })
    },
    assembleQueryParam() {
      console.log(this.queryParam.selecteddeparts)
      let selecteddeparts = this.queryParam.selecteddeparts
      if (selecteddeparts && selecteddeparts.length == 2) {
        this.queryParam.orgIds = selecteddeparts[0]
        this.queryParam.shopIds = selecteddeparts[1] == 0 ? null : selecteddeparts[1]
      } else {
        this.queryParam.orgIds = null
        this.queryParam.shopIds = null
      }

    },
    searchQuery1() {
      this.assembleQueryParam()

      this.loadData(1)
      this.querySum()
    },
    searchReset1() {
      this.init(true)
    },
    handleDetail(record) {
      this.$refs.modalForm.view(record.orderId, record.orgName)
      this.$refs.modalForm.title = '订单详情'
      this.$refs.modalForm.disableSubmit = false
    },
    handleChange(date, dateString) {
      this.queryParam.beginTime = dateString[0]
      this.queryParam.endTime = dateString[1]
    },
    filterOption(input, option) {
      return option.componentOptions.children[0].text.toLowerCase().indexOf(input.toLowerCase()) >= 0
    },
    querySum() {
      getAction(this.url.sumUrl, this.queryParam).then((res) => {
        if (res.success) {
          this.orderSum = res.result
        }
      })
    },
    checkExportParam() {
      let msg = "最多支持15天的数据导出"
      if (this.orderDateRange.length !== 2) {
        this.$message.warning(msg)
        return false
      }

      let beginTime = this.orderDateRange[0]
      let endTime = this.orderDateRange[1]
      let diffDays = endTime.diff(beginTime, 'day')
      if (diffDays > 15) {
        this.$message.warning(msg)
        return false
      }

      return true
    },
    handleExportXls1(fileName) {
      if (!this.checkExportParam()) {
        return
      }
      this.handleExportXls(fileName)
    },
    handleExportDetailXls(fileName) {
      if (!this.checkExportParam()) {
        return
      }

      if (!fileName || typeof fileName != 'string') {
        fileName = '导出文件'
      }
      let param = this.getQueryParams()
      if (this.selectedRowKeys && this.selectedRowKeys.length > 0) {
        param['selections'] = this.selectedRowKeys.join(',')
      }
      console.log('导出参数', param)
      downFile(this.url.exportDetailXlsUrl, param).then((data) => {
        if (!data) {
          this.$message.warning('文件下载失败')
          return
        }
        if (typeof window.navigator.msSaveBlob !== 'undefined') {
          window.navigator.msSaveBlob(new Blob([data], { type: 'application/vnd.ms-excel' }), fileName + '.xls')
        } else {
          let url = window.URL.createObjectURL(new Blob([data], { type: 'application/vnd.ms-excel' }))
          let link = document.createElement('a')
          link.style.display = 'none'
          link.href = url
          link.setAttribute('download', fileName + '.xls')
          document.body.appendChild(link)
          link.click()
          document.body.removeChild(link) //下载完成移除元素
          window.URL.revokeObjectURL(url) //释放掉blob对象
        }
      })
    },
  },
}
</script>
<style scoped lang="less">
@import '~@assets/less/common.less';
.sum {
  margin-right: 24px;
  .b {
    font-weight: 600;
    color: @primary-color;
  }
}
</style>